<template>
  <div class="market">
    <!-- 左侧区块，包含 K 线 和第一个热图 -->
    <div class="market_left">
      <div class="left_top">
        <div class="title_content">
          <div class="title_left">
            <p class="title_name">NDX</p>
            <p class="title_time">20915.70-197.00</p>
          </div>
          <div class="title_right">
            <i class="iconfont icon-xiajiang"></i>
            <span class="proportion">-0.933%</span>
          </div>
        </div>
        <!-- K 线容器 -->
        <div class="echarts_line">
          <div ref="chartRef" style="width: 100%; height: 100%;"></div>
          <!-- <div ref="chartContainer" style="width: 100%; height: 100%;"></div> -->
        </div>
      </div>

      <!-- 左下 热图 -->
      <div class="left_bottom">
        <p class="bottom_title">{{ Areachart0 }}</p>
        <div class="echarts_line">
          <div :ref="chartRefs.chart70" style="width: 100%; height: 90%;"></div>
        </div>
      </div>
    </div>

    <!-- 右侧区块，包含 3 个热图示例，可继续扩展 -->
    <div class="market_right">
      <p class="industries" style="width: 85%;margin: 0 auto;">{{ Areachart1 }}</p>
      <div class="echarts_line">
        <div :ref="chartRefs.chart72" style="width: 85%;margin: 0 auto; height: 175px;"></div>
      </div>
      <p class="industries" style="width: 85%;margin: 0 auto;">{{ Areachart2 }}</p>
      <div class="echarts_line">
        <div :ref="chartRefs.chart73" style="width: 85%;margin: 0 auto; height: 175px;"></div>
      </div>
      <p class="industries" style="width: 85%;margin: 0 auto;">{{ Areachart3 }}</p>
      <div class="echarts_line">
        <div :ref="chartRefs.chart74" style="width: 85%;margin: 0 auto; height: 175px;"></div>
      </div>
      <p class="industries" style="width: 85%;margin: 0 auto;">{{ Areachart4 }}</p>
      <div class="echarts_line">
        <div :ref="chartRefs.chart75" style="width: 85%;margin: 0 auto; height: 175px;"></div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, watch } from "vue"
import { marketKline, marketHeatmap } from '@/api/stock';



import * as echarts from 'echarts/core'
import { TitleComponent } from 'echarts/components'

// 按需引入两个图表类型
import { TreemapChart, LineChart } from 'echarts/charts'

// 按需引入用到的组件
import {
  TooltipComponent,
  GridComponent,
  DatasetComponent
} from 'echarts/components'

// 渲染器
import { CanvasRenderer } from 'echarts/renderers'

// 注册所有用到的模块
echarts.use([
  TreemapChart,     // 矩形树图
  LineChart,        // 折线图
  TooltipComponent, // 提示框
  GridComponent,    // 坐标轴、网格
  DatasetComponent, // dataset 功能
  CanvasRenderer, 
  TitleComponent  // 渲染器
])
// ----------------------------
// ✅ props: 支持多个热图数据
// ----------------------------

const Areachart0 = ref(null)
const Areachart1 = ref(null)
const Areachart2 = ref(null)
const Areachart3 = ref(null)
const Areachart4 = ref(null)


const chartRef = ref(null)



// ----------------------------
// ✅ 所有热图容器 ref
// ----------------------------
const chartRefs = {
  chart70: ref(null),
  chart72: ref(null),
  chart73: ref(null),
  chart74: ref(null),
  chart75: ref(null),
}

const mianjidata0 = ref([])
const mianjidata1 = ref([])
const mianjidata2 = ref([])
const mianjidata3 = ref([])
const mianjidata4 = ref([])

// ----------------------------
// ✅ 所有热图实例
// ----------------------------
const chartInstances = {
  chart70: null,
  chart72: null,
  chart73: null,
  chart74: null,
  chart75: null,
}
const klineData = ref([])
const marketKlineData = async () => {
  const res = await marketKline()
  if (res.code == 200) {

    let data = []
    res.data.forEach(item => {
      data.push(
        {
          date: item.date,
          type: 'NDX',
          price: item.close,
        }
      )
    });
    run(data)
  }
};

const get_Heatmap = async () => {
  const res = await marketHeatmap()
  console.log(res, 'resresres');
  if (res.code == 200) {


    let data0 = []
    let data1 = []
    let data2 = []
    let data3 = []
    let data4 = []
    res.data.forEach((item, index) => {
      if (index === 0) {
        Areachart0.value = item.enName;
        item.stockData.forEach(im => {

          let baifenbi0 = (im.priceNominal - im.priceLast) / im.priceLast * 100;
          baifenbi0 = formatToTwoDecimal(baifenbi0);

          // 🎯 根据 baifenbi0 判断颜色
          let blockColor = '';
          if (baifenbi0 > 1) {
            blockColor = '#74c476'; // 绿色，大于1
          } else if (baifenbi0 > 0) {
            blockColor = '#addd8f'; // 浅绿色，0~1
          } else if (baifenbi0 > -1) {
            blockColor = '#ffd8db'; // 浅红色，0~-1
          } else {
            blockColor = '#fcb9b6'; // 红色，小于-1
          }

          data0.push({
            name: im.symbol,
            value: Math.abs(baifenbi0),  // treemap 用绝对值占比
            price: baifenbi0.toFixed(2), // 原始涨跌幅显示
            itemStyle: {
              color: blockColor          // 按区间设置块颜色
            }
          });
        });
      }
      if (index === 1) {
        Areachart1.value = item.enName
        item.stockData.forEach(im => {
          let baifenbi1 = formatToTwoDecimal((im.priceNominal - im.priceLast) / im.priceLast * 100)

          // 🎯 根据 baifenbi1 判断颜色
          let blockColor = '';
          if (baifenbi1 > 1) {
            blockColor = '#74c476'; // 绿色，大于1
          } else if (baifenbi1 > 0) {
            blockColor = '#addd8f'; // 浅绿色，0~1
          } else if (baifenbi1 > -1) {
            blockColor = '#ffd8db'; // 浅红色，0~-1
          } else {
            blockColor = '#fcb9b6'; // 红色，小于-1
          }
          data1.push(
            {
              name: im.symbol,
              value: Math.abs(baifenbi1),
              price: baifenbi1.toFixed(2),
              itemStyle: {
                color: blockColor          // 按区间设置块颜色
              }
            }
          )
        });
      }
      if (index === 2) {

        Areachart2.value = item.enName
        item.stockData.forEach(im => {
          let baifenbi2 = formatToTwoDecimal((im.priceNominal - im.priceLast) / im.priceLast * 100)
          // 🎯 根据 baifenbi2 判断颜色
          let blockColor = '';
          if (baifenbi2 > 1) {
            blockColor = '#74c476'; // 绿色，大于1
          } else if (baifenbi2 > 0) {
            blockColor = '#addd8f'; // 浅绿色，0~1
          } else if (baifenbi2 > -1) {
            blockColor = '#ffd8db'; // 浅红色，0~-1
          } else {
            blockColor = '#fcb9b6'; // 红色，小于-1
          }
          data2.push(
            {
              name: im.symbol,
              value: Math.abs(baifenbi2),
              price: baifenbi2.toFixed(2),
              itemStyle: {
                color: blockColor          // 按区间设置块颜色
              }
            }
          )
        });
      }
      if (index === 3) {

        Areachart3.value = item.enName
        item.stockData.forEach(im => {
          let baifenbi3 = formatToTwoDecimal((im.priceNominal - im.priceLast) / im.priceLast * 100)

          // 🎯 根据 baifenbi3 判断颜色
          let blockColor = '';
          if (baifenbi3 > 1) {
            blockColor = '#74c476'; // 绿色，大于1
          } else if (baifenbi3 > 0) {
            blockColor = '#addd8f'; // 浅绿色，0~1
          } else if (baifenbi3 > -1) {
            blockColor = '#ffd8db'; // 浅红色，0~-1
          } else {
            blockColor = '#fcb9b6'; // 红色，小于-1
          }

          data3.push(
            {
              name: im.symbol,
              value: Math.abs(baifenbi3),
              price: baifenbi3.toFixed(2),
              itemStyle: {
                color: blockColor          // 按区间设置块颜色
              }
            }
          )
        });
      }

      if (index === 4) {

        Areachart4.value = item.enName
        item.stockData.forEach(im => {
          let baifenbi4 = formatToTwoDecimal((im.priceNominal - im.priceLast) / im.priceLast * 100)

          // 🎯 根据 baifenbi4 判断颜色
          let blockColor = '';
          if (baifenbi4 > 1) {
            blockColor = '#74c476'; // 绿色，大于1
          } else if (baifenbi4 > 0) {
            blockColor = '#addd8f'; // 浅绿色，0~1
          } else if (baifenbi4 > -1) {
            blockColor = '#ffd8db'; // 浅红色，0~-1
          } else {
            blockColor = '#fcb9b6'; // 红色，小于-1
          }

          data4.push(
            {
              name: im.symbol,
              value: Math.abs(baifenbi4),
              price: baifenbi4.toFixed(2),
              itemStyle: {
                color: blockColor          // 按区间设置块颜色
              }
            }
          )
        });
      }

    });

    mianjidata0.value = data0
    mianjidata1.value = data1
    mianjidata2.value = data2
    mianjidata3.value = data3
    mianjidata4.value = data4


    initTreemapChart('chart70', mianjidata0)
    initTreemapChart('chart72', mianjidata1)
    initTreemapChart('chart73', mianjidata2)
    initTreemapChart('chart74', mianjidata3)
    initTreemapChart('chart75', mianjidata4)


  }
};


function formatToTwoDecimal(value) {
  return Math.round(value * 100) / 100;
}

// ----------------------------
// ✅ 热力通用初始化函数
// ----------------------------
function initTreemapChart(refKey, data) {

  const refEl = chartRefs[refKey]
  if (!refEl.value) return

  const instance = echarts.init(refEl.value)
  chartInstances[refKey] = instance

  const total = data.value.reduce((sum, item) => sum + item.value, 0)

  instance.setOption({
    tooltip: {
      formatter: info => {
        const { name, price
        } = info.data
        // const percent = ((value / total) * 100).toFixed(2)
        return `${name}: ${price}%`
      },
    },
    // color: ['#1d2a95', '#174093', '#1a44df', '#1f63d9', '#5477fa'],
    series: [
      {
        type: 'treemap',
        data: data.value,
        roam: false,
        nodeClick: false,
        label: {
          show: true,
          position: 'inside',
          align: 'center',
          verticalAlign: 'middle',
          formatter: params => {
            // const percent = ((params.value / total) * 100).toFixed(1)
            const ratio = params.value / total
            if (ratio > 0.04) {
              const price = params.data.price
              const priceColorKey = price >= 0 ? 'positivePrice' : 'negativePrice'
              return `${params.name}\n{${priceColorKey}|${price}%}`
            } else {
              return `${params.name}`
            }
          },
          color: '#333',
          fontSize: 14,
          fontWeight: 'bold',
          rich: {
            positivePrice: {
              color: 'green', // 只有价格用 rich 单独换颜色
              fontSize: 13,
              fontWeight: 'bold',
            },
            negativePrice: {
              color: 'red', // 负数绿色
              fontSize: 13,
              fontWeight: 'bold',
            },
          },
        },
        labelLayout: params => {
          if (params.rect.height < 42) {
            return {
              x: params.rect.x + params.rect.width / 2,
              y: params.rect.y + params.rect.height / 1.6,
              align: 'center',
              verticalAlign: 'middle',
            };
          } else {
            return {
              x: params.rect.x + params.rect.width / 2,
              y: params.rect.y + params.rect.height / 1.2,
              align: 'center',
              verticalAlign: 'middle',
            };
          }

        },
        breadcrumb: { show: false },
        paddingInner: 0,
        itemStyle: {
          borderColor: '#18191e',
          borderWidth: 2,
          borderRadius: 10,
        },
        left: 0,
        right: 0,
        top: 0,
        bottom: 0,
      },
    ],
  })

  instance.on('click', params => {
    console.log(`点击 ${refKey}:`, params.data)
  })

  window.addEventListener('resize', () => {
    instance.resize()
  })
}

// ----------------------------
// ✅ 各热图数据变化时自动更新
// ----------------------------
watch(() => mianjidata0, () => {
  initTreemapChart('chart70', mianjidata0)
})
watch(() => mianjidata1, () => {
  initTreemapChart('chart72', mianjidata1)
})
watch(() => mianjidata2, () => {
  initTreemapChart('chart73', mianjidata2)
})
watch(() => mianjidata3, () => {
  initTreemapChart('chart74', mianjidata3)
})

watch(() => mianjidata4, () => {
  initTreemapChart('chart75', mianjidata4)
})

// ----------------------------
// ✅ K 线图容器
// ----------------------------
function run(lineData) {
  const myChart = echarts.init(chartRef.value);

  const option = {
    dataset: [
      {
        id: 'dataset_raw',
        source: lineData
      }
    ],
    title: { show: false },
    tooltip: {
      textStyle: {
        color: '#ffffff' // 这里改成你想要的颜色
      },
      trigger: 'axis',
      backgroundColor: 'transparent', // 设置背景透明
      borderWidth: 0,                 // 去掉边框（可选）
      axisPointer: {
        type: 'line'
      },
      marker: false, // 去掉悬浮蓝色小圆点
      formatter: params => {
        const data = params[0]
        const date = new Date(data.value.date);
        const dateStr = date.toISOString().slice(0, 10); // 只要年月日部分
        const price = data.value.price;
        return `${dateStr}<br/>Price: ${price}`;
      }
    },
    xAxis: {
      show: false,
      type: 'time' // 时间轴
    },
    yAxis: {
      show: false,
      type: 'value',
      name: 'Price'
    },
    grid: { left: 0, right: 0, top: 0, bottom: 0 },
    series: [
      {
        type: 'line',
        datasetId: 'dataset_raw',
        showSymbol: false,
        encode: {
          x: 'date',
          y: 'price',
          itemName: 'date',
          tooltip: ['price']
        },
        lineStyle: {
          width: 2,
          color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
            { offset: 0, color: '#fe554f' },
            { offset: 1, color: '#fe554f' }
          ])
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(135, 54, 53, 0.5)' },
            { offset: 0.2, color: 'rgba(121, 49, 49, 0.5)' },
            { offset: 0.4, color: 'rgba(101, 44, 44, 0.5)' },
            { offset: 0.6, color: 'rgba(93, 42, 43, 0.5)' },
            { offset: 0.8, color: 'rgba(50, 29, 32, 0.5)' },
            { offset: 1, color: 'rgba(30, 24, 28, 0)' }
          ])
        }
      }
    ]
  };

  myChart.setOption(option);
}



// ----------------------------
// ✅ 挂载后初始化 K 线和热图
// ----------------------------
onMounted(() => {
  marketKlineData()
  // get_Areachart()
  get_Heatmap()
  setTimeout(() => {
    console.log(klineData, 'klineData');
  }, 2500);

})

// ----------------------------
// ✅ 卸载时销毁
// ----------------------------
onBeforeUnmount(() => {
  Object.keys(chartInstances).forEach(key => {
    chartInstances[key]?.dispose()
    chartInstances[key] = null
  })
})
</script>


<style scoped lang="less">
.market {
  //   height: 100%;
  height: calc(100vh - 60px - 30px - 10px);
  // background-color:blue;
  display: flex;
  overflow-y: hidden !important;

  .market_left {
    width: 680px;
    min-width: 680px;
    height: calc(100vh - 110px);
    display: flex;
    flex-direction: column;

    .left_top {
      width: 100%;
      height: 45%;

      //   border:1px solid green;
      .title_content {
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 15px 0;

        .title_left {
          display: flex;
          align-items: center;
          font-weight: 700;

          .title_name {
            color: #fff;
            margin-right: 10px;
            font-size: 18px;
          }

          .title_time {
            font-size: 18px;
            color: rgb(254, 85, 79);
          }
        }

        .title_right {
          display: flex;
          align-items: center;
          color: rgb(254, 85, 79);

          .icon-xiajiang {
            font-size: 14px;
          }

          .proportion {
            font-weight: 700;
            font-size: 18px;
          }
        }
      }

      .echarts_line {
        width: 100%;
        height: calc(100% - 56px);
        // border: 1px solid red;
      }
    }

    .left_bottom {
      width: 100%;
      flex: 1;

      .bottom_title {
        padding: 10px 0;
        font-size: 18px;
        color: #fff;
      }

      .echarts_line {
        width: 100%;
        height: calc(100% - 86px);
        display: flex;
        flex-direction: column;
        justify-content: center;
      }

    }
  }

  .market_right {
    flex: 1;
    margin: 15px 15px 0 15px;
    padding: 15px 15px 0 15px;
    height: calc(100vh - 10px);
    background-color: #202b2c;
    overflow: hidden;
    overflow-y: auto;
    min-width: 800px;
    height: calc(100vh - 110px - 60px);

    .industries {
      font-size: 18px;
      color: #fff;
    }

  }
}
</style>
